package com.zsd.android.okhttplib.chain;

import android.text.TextUtils;

import com.zsd.android.okhttplib.Request;
import com.zsd.android.okhttplib.Response;
import com.zsd.android.okhttplib.SocketRequestServer;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;

import javax.net.ssl.SSLSocketFactory;

/**
 * 连接服务器拦截器
 */
public class ConnectionServerInterceptor implements Interceptor {

    @Override
    public Response doNext(Chain chain) throws IOException {
        SocketRequestServer server = new SocketRequestServer();
        Request request = chain.getRequest();
        //只能访问HTTP，不能访问HTTPS SSL握手
        Socket socket = new Socket(server.getHost(request), server.getPort(request));
        String result = server.queryHttpOrHttps(request.getUrl());
        if (!TextUtils.isEmpty(result) && "HTTPS".equalsIgnoreCase(result)) {
            //修改成可以访问HTTPS的Socket
            socket = SSLSocketFactory.getDefault().createSocket(server.getHost(request), server.getPort(request));
        }
        //todo 请求
        //output
        OutputStream os = socket.getOutputStream();
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
        //给服务器发送请求
        String requestHeaderAll = server.getRequestHeaderAll(request);
        bw.write(requestHeaderAll);
        //真正的写出去....
        bw.flush();

        //todo 响应
        //input
        InputStream is = socket.getInputStream();
        final BufferedReader br = new BufferedReader(new InputStreamReader(is));
        Response response = new Response();
        //todo 取出响应码
        String readLine = br.readLine();
        //HTTP/1.1 200 OK
        String[] split = readLine.split(" ");
        response.setCode(Integer.parseInt(split[1]));
        //todo 取出响应体, 只要是空行，下面的就是响应体
        while ((readLine = br.readLine()) != null) {
            if ("".equals(readLine)) {
                //读到空行了,就代表下面的就是响应体
                response.setBody(br.readLine());
                break;
            }
        }
        return response;
    }
}
